import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { routes } from '@/router/route'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 禁止跳转到登录页（如果已经登陆）
  if (!(await authStore.getTokenAction()) && to.path !== '/login' && from.path !== '/login') {
    next('/login')
    return
  } else if ((await authStore.getTokenAction()) && to.path === '/login') {
    next(from.path)
    return
  } else {
    next()
    return
  }
})

export default router
